package com.binarysnobbery.ymmv.server;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import java.util.Date;
import com.binarysnobbery.ymmv.client.MileageEntry;
import com.binarysnobbery.ymmv.client.NotLoggedInException;
import com.binarysnobbery.ymmv.client.TrackerService;

public class TrackerServiceImpl extends RemoteServiceServlet implements
		TrackerService {

	private static final Logger LOG = Logger.getLogger(TrackerServiceImpl.class.getName());
	private static final PersistenceManagerFactory PMF =
		JDOHelper.getPersistenceManagerFactory("transactions-optional");
	
	@Override
	public void addMileageEntry(Date date, double gallons, double miles) throws NotLoggedInException {
		checkLoggedIn();
		PersistenceManager pm = getPersistenceManager();
		try {
			pm.makePersistent(new MileageEntry(getUser(), date, gallons, miles));
		} finally {
			pm.close();
		}

	}

	@Override
	public MileageEntry[] getEntries() throws NotLoggedInException {
		checkLoggedIn();
		PersistenceManager pm = getPersistenceManager();
		List<MileageEntry> mileageEntries = new ArrayList<MileageEntry>();
		try {
			Query q = pm.newQuery(MileageEntry.class, "user == u");
			q.declareParameters("com.google.appengine.api.users.User u");
			q.setOrdering("dateStamp");
			List<MileageEntry> entries = 
				(List<MileageEntry>) q.execute(getUser());
			for (MileageEntry entry : entries) {
				mileageEntries.add(entry);
			}
		} finally {
			pm.close();
		}
		return (MileageEntry[]) mileageEntries.toArray(new MileageEntry[0]);
	}

	private void checkLoggedIn() throws NotLoggedInException {
		if (getUser() == null) {
			throw new NotLoggedInException("Not logged in.");
		}
	}
	private User getUser() {
		UserService userService = UserServiceFactory.getUserService();
		return userService.getCurrentUser();
	}
	
	private PersistenceManager getPersistenceManager() {
		return PMF.getPersistenceManager();
	}
}
